package net.xdclass.service.impl;

import lombok.extern.slf4j.Slf4j;
import net.xdclass.controller.request.AccountLoginRequest;
import net.xdclass.controller.request.AccountRegisterRequest;
import net.xdclass.enums.AuthTypeEnum;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.enums.SendCodeEnum;
import net.xdclass.manager.AccountManager;
import net.xdclass.model.AccountDO;
import net.xdclass.mapper.AccountMapper;
import net.xdclass.model.LoginUser;
import net.xdclass.service.AccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.xdclass.service.NotifyService;
import net.xdclass.util.CommonUtil;
import net.xdclass.util.IDUtil;
import net.xdclass.util.JWTUtil;
import net.xdclass.util.JsonData;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 小冯
 * @since 2023-06-18
 */
@Service
@Slf4j
public class AccountServiceImpl extends ServiceImpl<AccountMapper, AccountDO> implements AccountService {

    @Autowired
    private NotifyService notifyService;

    @Autowired
    private AccountManager accountManager;

    /**
     * 用户注册
     * 手机验证码验证
     * 密码加密（TODO）
     * 账号唯一性检查(TODO)
     * 插入数据库
     * 新注册用户福利发放(TODO)
     *
     * @param request
     * @return
     */
    @Override
    public JsonData register(AccountRegisterRequest request) {
        boolean checkCode = false;
        // 手机验证码验证
        String code = request.getCode();
        if (StringUtils.isNotBlank(request.getPhone())) {
             checkCode = notifyService.checkCode(SendCodeEnum.USER_REGIDTER,request.getPhone(),code);
        }
        if (!checkCode) {
            return JsonData.buildError(BizCodeEnum.CODE_ERROR.name());
        }
        AccountDO accountDO = new AccountDO();
        BeanUtils.copyProperties(request, accountDO);
        //认证级别
        accountDO.setAuth(AuthTypeEnum.DEFAULT.name());
        //生成唯一的账号
        accountDO.setAccountNo(Long.valueOf(IDUtil.geneSnowFlakeID().toString()));
        //密码加密
        accountDO.setSecret("$1$"+ CommonUtil.getStringNumRandom(8));
        String cryptPwd = Md5Crypt.md5Crypt(request.getPwd().getBytes(), accountDO.getSecret());
        accountDO.setPwd(cryptPwd);

        // 插入数据库
        int rows = accountManager.insert(accountDO);
        log.info("注册成功",rows,accountDO);
        // 新注册用户福利发放(TODO)
        this.userRegisterInitTask(accountDO);

        return JsonData.buildSuccess();
    }

    /**
     * 登录
     * @param request
     * @return
     */
    @Override
    public JsonData login(AccountLoginRequest request) {
        List<AccountDO> byPhone = accountManager.findByPhone(request.getPhone());
        if (byPhone != null && byPhone.size() == 1) {
            AccountDO accountDO = byPhone.get(0);
            String md5Crypt = Md5Crypt.md5Crypt(request.getPwd().getBytes(), accountDO.getSecret());
            if (md5Crypt.equalsIgnoreCase(accountDO.getPwd())) {
                //创建LoginUser对象
                LoginUser user = LoginUser.builder().build();
                BeanUtils.copyProperties(accountDO, user);
                //生成token
                String token = JWTUtil.geneJsonWebToken(user);
                return JsonData.buildSuccess(token);
            } else {
                return JsonData.buildError(BizCodeEnum.ACCOUNT_PWD_ERROR.name());
            }
        }
        return JsonData.buildResult(BizCodeEnum.ACCOUNT_PWD_ERROR);
    }

    private void userRegisterInitTask(AccountDO accountDO) {

    }
}
